<?php

namespace App\Http\Controllers;

use App\Models\Address;
/*use App\Models\Details;*/

use App\Models\Comment;
use App\Models\Detail;
use App\Models\Match;
use App\Models\Order;
use App\Models\Cart;
use App\Traits\ApiResponse;
use App\User;
use DB;
use Illuminate\Http\Request;

class OrderController extends Controller
{

    use ApiResponse;

    public function store(Request $request)
    {
        $this->validate($request, [
            'goods_match' => 'required|array',
            'address_id' => 'required|int',
        ], [
            'goods_match' => 'required|array',
            'address_id.*' => '选择收货地址',
        ]);

        if (empty($request['goods_match'])) {
            return $this->error('');

        }
        $ids = [];
        foreach ($request['goods_match'] as $id => $number) {
            $ids[] = $id;
        }
        $user = $request->user();
        $goodsMatch = Match::query()->with('goods')->whereIn('id', $ids)->get();
        if ($goodsMatch->count() == 0) {
            return $this->error('库存不足');
        }
        $totalPrice = 0;

        $detailData = [];

        foreach ($goodsMatch as $item) {
            $totalPrice = bcadd(bcmul($item->goods->price, $request['goods_match'][$item->id], 2), $totalPrice, 2);
            // TODO 此方法不严谨，并发情况会出问题
            if ($item->num < $request['goods_match'][$item->id]) {
                return $this->error('库存不足!');
            }
            $detailData[] = [
                'goods_id' => $item->goods->goods_id,
                'goods_match_id' => $item->id,
                'num' => $request['goods_match'][$item->id],
                'totalprice' => $totalPrice,
                'user_id' => $user->id,
                'goods_name' => $item->goods->name,
                'time' => date("Y-m-d H:i:s"),
//                'order_id' => $item->goods->goods_id,
            ];
        }

        try {
            DB::beginTransaction();
            $order = Order::query()->create([
                'time' => date("Y-m-d H:i:s"),
                'user_id' => $user->id,
                'order_state' => Order::STATUS_NORMAL,
                'totalprice' => $totalPrice,
                'goods_id' => '0',
                'address_id' => $request['address_id'],

            ]);
            foreach ($detailData as $key => $item) {
                $detailData[$key]['order_id'] = $order->order_id;
            }
            Detail::query()->insert($detailData);
            Cart::query()->whereIn('goods_match_id', $ids)->delete();
            foreach ($request['goods_match'] as $id => $number) {
                Match::query()->where('id', $id)->decrement('num', (int)$number);
            }
            DB::commit();
        } catch (\Throwable $throwable) {
            DB::rollback();
            return $this->error($throwable->getMessage());
        }
        return $this->success();

    }

    public function create(Request $request)
    {
        $user = $request->user();
        $address = Address::where('user_id', $user->id)->get();

        $goodsMatch = $this->getCartGoods($user);
        $totalPrice = 0.0;

        foreach ($goodsMatch as $item) {
            $totalPrice = bcadd($totalPrice, bcmul($item->price, $item->num, 2), 2);
        }
        return view('order.create', [
            'address' => $address,
            'goodsMatch' => $goodsMatch,
            'totalPrice' => $totalPrice,
        ]);
    }

    public function getCartGoods(User $user)
    {
        $goods = Cart::query()->leftJoin('tb_match', 'tb_cart.goods_match_id', '=', 'tb_match.id');
        $goods->leftJoin('tb_goods', 'tb_goods.goods_id', '=', 'tb_match.goods_id');
        $goods->where('tb_cart.user_id', $user->id);
        /*$goods->where('tb_detail.order_id', 0);*/
        $goods->where('tb_cart.is_checked', 1);

        return $goods->select('tb_cart.num', 'tb_match.size',
            'tb_match.color', 'tb_goods.pic', 'tb_goods.name', 'tb_goods.price', 'tb_goods.goods_id', 'tb_cart.goods_match_id')->get();
    }

    public function index(Request $request)
    {
        $orders = Order::query()->where('user_id', $request->user()->id);

        if ($request['order_state']) {
            $orders->where('order_state', $request['order_state']);
        }
        if ($request['order_id']) {
            $orders->where('order_id', $request['order_id']);
        }
        $orders = $orders->orderBy('time', 'DESC')->paginate(6);
        return view('order.index', ['orders' => $orders]);
    }

    public function show(Request $request)
    {
        $order = Order::query()->where('user_id', $request->user()->id)->where('order_id', $request['order_id'])->firstOrFail();


        $goodsMatch = Detail::query()
            ->leftJoin('tb_match', 'tb_match.id', '=', 'tb_detail.goods_match_id')
            ->leftJoin('tb_goods', 'tb_goods.goods_id', '=', 'tb_detail.goods_id')
            ->where('order_id', $order->order_id)
            ->select('tb_detail.num', 'tb_detail.totalprice', 'tb_match.color', 'tb_match.size', 'tb_goods.pic', 'tb_goods.name', 'tb_goods.price')
            ->get();


        $address = Address::query()->where('id', $order->address_id)->first();
        $comment = Comment::query()->where('order_id', $order->order_id)->first();
        return view('order.show', [
            'order' => $order,
            'address' => $address,
            'goodsMatch' => $goodsMatch,
            'comment' => $comment,
        ]);
    }


    public function pay(Request $request)
    {
        $order = Order::query()->where('order_id', $request['order_id'])->first();
        if (!$order && $order->order_state != Order::STATUS_NORMAL) {
            return $this->error('订单异常');
        }
        $order->order_state = Order::STATUS_PAYED;
        $order->save();
        return $this->success();
    }

    // 买家收货 订单完成
    public function complete(Request $request)
    {
        $order = Order::query()->where('order_id', $request['order_id'])->first();
        if (!$order && $order->order_state != Order::STATUS_SHIPPING) {
            return $this->error('订单异常');
        }
        $order->order_state = Order::STATUS_COMPLETE;
        $order->save();
        return $this->success();
    }

    public function payView(Request $request)
    {
        $order = Order::query()->where('order_id', $request['order_id'])->first();
        if (!$order && $order->order_state != Order::STATUS_NORMAL) {
            return $this->error('订单异常');
        }
        return view('order.pay', [
            'order' => $order,
        ]);
    }
}
